# -*- coding: utf-8 -*-
# 服务器端，用以处理五子棋棋盘信息通信
import socket
from flask import Flask, request
from Gomoku import *

app = Flask(__name__)

LINES = 19
board = Board(LINES)

board_dict_send = {'board': board.getBoard(),
                   'runner': 'black',
                   'win': 0}

board_dict_rec = {'x': -1,
                  'y': -1}

current_runner = BLACK_CHESSMAN
win = 0


@app.route('/')
def index():
    return "Hello Goumuku!"


@app.route('/board', methods=['GET'])
def getBoard():
    global board, current_runner, win, board_dict_send

    board_dict_send['board'] = board.getBoard()
    board_dict_send['runner'] = current_runner.name
    board_dict_send['win'] = win
    return board_dict_send


@app.route('/board', methods=['POST'])
def setBoard():
    global board, current_runner, win, board_dict_rec

    new_x = int(request.form['x'])
    new_y = int(request.form['y'])

    if new_x == -1 or new_y == -1:
        board = Board(LINES)
        current_runner = BLACK_CHESSMAN
        win = 0
        return 'successfully reset'

    point = Point(new_x, new_y)
    winner = board.drop(current_runner, point)
    if winner is None:
        current_runner = getNextRunner(current_runner)
        win = 0
    else:
        if winner == BLACK_CHESSMAN:
            win = 1
        elif winner == WHITE_CHESSMAN:
            win = 2
            pass
        pass

    return 'successfully post'


def get_host_ip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()
        pass
    return ip


if __name__ == '__main__':
    server_ip = get_host_ip()
    print('server_ip is: ' + server_ip)

    app.run(host='0.0.0.0', port='5000')
    # app.run(port='5000')
    pass
